package com.example.demo.controller;

import com.example.demo.domain.Class;

import com.example.demo.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 86132
 */
@Controller
@RequestMapping("/pri/class")
public class ClassController {

    @Autowired
    private ClassService classService;
    @GetMapping("/findAll")
    public String findAll(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize,
                          Model model){
        Integer totalPage = null;
        pageNum = (pageNum-1)*pageSize;
        List<Class> ClassList = classService.findAll(pageNum,pageSize);
        Integer pageTotal = classService.findTotalRecord();
        model.addAttribute("ClassList",ClassList);
        //实行分页
        if(pageTotal % pageSize == 0){
            totalPage = pageTotal / pageSize;
        }else{
            totalPage = pageTotal / pageSize + 1;
        }
        model.addAttribute("totalPage",totalPage);
        return "/class/list";
    }


    @GetMapping("/delete")
    public String delete(HttpServletRequest request){
        int cid = Integer.parseInt(request.getParameter("cid"));
       int id = Integer.parseInt(request.getParameter("id"));
        classService.delete(cid,id);
        return "redirect:/pri/class/findAll";
    }


    @GetMapping("/toAdd")
    public String toAdd(Model model){
        model.addAttribute("class", new Class());
        return "class/add";
    }

    @PostMapping("/add")
    public String add(Class classes){
        classService.add(classes);
        return "redirect:/pri/class/findAll";
    }

    @GetMapping("/toUpdate")
    public String toUpdate(HttpServletRequest request, Model model){
       int cid = Integer.parseInt(request.getParameter("cid"));
        int id = Integer.parseInt(request.getParameter("id"));
        Class classes = classService.findClassByCid(cid,id);
        model.addAttribute("classes",classes);
        return "/class/modify";
    }

    @PostMapping("/update")
    public String update(Class classes){
        classService.update(classes);
        return "redirect:/pri/class/findAll";
    }

}